package com.studyyoun.android.nonghe.welcom.activity;
/**
 * Created by zhaolong on 2017/10/3.
 * 站在顶峰，看世界
 * 落在谷底，思人生
 */

import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.studyyoun.android.androidcommonbaselibrary.activity.CommonBaseActivity;
import com.studyyoun.android.androidcommonbaselibrary.okhttp.callback.OkhttpCommonCallBack;
import com.studyyoun.android.androidcommonbaselibrary.okhttp.client.OkhttpCommonClient;
import com.studyyoun.android.androidcommonbaselibrary.utils.AnimationUtils;
import com.studyyoun.android.androidcommonbaselibrary.utils.CommonLoadingUtils;
import com.studyyoun.android.androidcommonbaselibrary.utils.LogUtils;
import com.studyyoun.android.androidcommonbaselibrary.utils.SharedPreferencesUtil;
import com.studyyoun.android.androidcommonbaselibrary.utils.ToastUtils;
import com.studyyoun.android.nonghe.R;
import com.studyyoun.android.nonghe.http.HttpUrlHelper;
import com.studyyoun.android.nonghe.welcom.App;
import com.studyyoun.android.nonghe.welcom.CommonUserHelper;
import com.studyyoun.android.nonghe.welcom.model.UserModel;

import java.util.concurrent.ConcurrentHashMap;

import cn.smssdk.EventHandler;
import cn.smssdk.OnSendMessageHandler;
import cn.smssdk.SMSSDK;

/**
 * class infation
 * 注册页面
 */
public class RegistActivity extends CommonBaseActivity {

    private TextView mHeaderTitleTextView;
    private LinearLayout mBackLinearLayout;
    private RelativeLayout mHeaderRelativeLayout;
    private TextView mWelcomeTextView;
    private LinearLayout mUserNameLinearLayout;
    private LinearLayout mCheckCodeLinearLayout;
    private Button mLoginButton;
    private EditText mUserNameEditText;
    private Button mCheckCodeButton;
    private EventHandler mEventHandler;
    private EditText mCheckCodeEditText;

    @Override
    protected void getAllIntentExtraDatas(Intent intent) {

    }

    @Override
    protected int getCommonLayoutId() {
        return R.layout.activity_regist_layout;
    }

    @Override
    protected void commonInitView(View view) {

        mHeaderTitleTextView = findViewById(R.id.tv_base_header_title);
        mBackLinearLayout = findViewById(R.id.ll_base_back);
        mHeaderRelativeLayout = findViewById(R.id.rl_login_header);
        mHeaderRelativeLayout.setVisibility(View.INVISIBLE);

        mWelcomeTextView = findViewById(R.id.tv_login_header_title);
        mWelcomeTextView.setVisibility(View.INVISIBLE);

        mUserNameLinearLayout = findViewById(R.id.ll_login_username);
        mUserNameLinearLayout.setVisibility(View.INVISIBLE);
        mCheckCodeLinearLayout = findViewById(R.id.ll_login_check_code_input);
        mCheckCodeLinearLayout.setVisibility(View.INVISIBLE);


        mUserNameEditText = findViewById(R.id.et_login_username_input);

        mLoginButton = findViewById(R.id.tv_commit_login_data);
        mLoginButton.setVisibility(View.INVISIBLE);

        mCheckCodeButton = findViewById(R.id.bt_login_check_code_input);
        mCheckCodeEditText = findViewById(R.id.et_login_check_code_input);
    }

    @Override
    protected void commonFunction() {
        mHeaderTitleTextView.setText("验证码登录");
        mBackLinearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    @Override
    protected void commonDelayFunction() {

        AnimationUtils.initLeftToRightAnimationFunction(mWelcomeTextView, 500, 10);

        AnimationUtils.initLeftToRightAnimationFunction(mUserNameLinearLayout, 500, 200);
        AnimationUtils.initRightToLeftAnimationFunction(mCheckCodeLinearLayout, 500, 300);
        AnimationUtils.initAlphaAnimation(mLoginButton, 500, 500);
        AnimationUtils.initAlphaAnimation(mHeaderRelativeLayout, 500, 500);

        String userName = SharedPreferencesUtil.getInstance(mContext).getData("userName");
        mUserNameEditText.setText(userName);
        mUserNameEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                String string = charSequence.toString();
                if (!TextUtils.isEmpty(string) && string.length() == 11) {
                    SharedPreferencesUtil.getInstance(mContext).saveData("userName", string);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        mCheckCodeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String mobile = mUserNameEditText.getText().toString();
                if (TextUtils.isEmpty(mobile)) {
                    ToastUtils.show("请输入手机号", mContext);
                    return;
                }
                SMSSDK.getVerificationCode("86", mobile, new OnSendMessageHandler() {
                    @Override
                    public boolean onSendMessage(String s, String s1) {
                        LogUtils.d("" + s + "    " + s1);
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtils.show("短信已发送，请注意查收 ", mContext);
                            }
                        });

                        return false;
                    }
                });
            }
        });

        initMobileFunction();

        mLoginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String userName = mUserNameEditText.getText().toString();
                String checkCode = mCheckCodeEditText.getText().toString();

                if (TextUtils.isEmpty(userName) || userName.length() < 11) {
                    ToastUtils.show("请输入标准的手机号", mContext);
                    return;
                } else if (TextUtils.isEmpty(checkCode)) {
                    ToastUtils.show("请输入验证码", mContext);
                    return;
                }

                SMSSDK.submitVerificationCode("86", userName, checkCode);
            }
        });

    }

    private void initMobileFunction() {

        // 如果希望在读取通信录的时候提示用户，可以添加下面的代码，并且必须在其他代码调用之前，否则不起作用；如果没这个需求，可以不加这行代码
        SMSSDK.setAskPermisionOnReadContact(false);

        // 创建EventHandler对象
        // 处理你自己的逻辑
        mEventHandler = new EventHandler() {
            public void afterEvent(final int event, final int result, final Object data) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (event == 472) {
                            ToastUtils.show("送短信验证过于频繁,请稍后再试", mContext);
                            return;
                        } else if (event == 467) {
                            ToastUtils.show("校验验证码请求频繁,请稍后再试", mContext);
                            return;
                        } else if (event == 463 || event == 464 || event == 465) {
                            ToastUtils.show("验证码请求频繁,请稍后再试", mContext);
                            return;
                        }
                        if (data instanceof Throwable) {
                            Throwable throwable = (Throwable) data;
                            String msg = throwable.getMessage();
                            LogUtils.e(msg);
                        } else {
                            if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                                // 处理你自己的逻辑
                                LogUtils.d("" + data);
                                if (result == SMSSDK.RESULT_COMPLETE) {
                                    boolean smart = (Boolean) data;
                                    if (smart) {
                                        //通过智能验证
                                        ToastUtils.show("智能验证成功 ", mContext);
                                        loginFunction();
                                    } else {
                                        //依然走短信验证
                                    }
                                }
                            } else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {
                                LogUtils.d("GET SUPPECT COUNT " + data);
                            } else if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                                //提交验证码
                                loginFunction();
                            } else {
                                LogUtils.e(" " + event + "  " + result + "  " + data.toString());
                            }
                        }
                    }
                });

            }
        };

        // 注册监听器
        SMSSDK.registerEventHandler(mEventHandler);

    }

    private long mPreTime;

    /**
     * 短信登录功能
     */
    private void loginFunction() {

        String userName = mUserNameEditText.getText().toString();
        mPreTime = System.currentTimeMillis();
        CommonLoadingUtils.getInstance().showLoading(mWelcomeTextView);
        ConcurrentHashMap<String, String> key = new ConcurrentHashMap<>();
        key.put("userName", userName);
        String url = HttpUrlHelper.sCheckCodeLoginUrl;
        OkhttpCommonClient.sentPostRequest(url, key, new OkhttpCommonCallBack(UserModel.class) {
            @Override
            public void onSuccess(final Object obj) {

                long flagTime = System.currentTimeMillis() - mPreTime;
                if (flagTime < 1500) {
                    flagTime = 1500 - flagTime;
                } else {
                    flagTime = 0;
                }
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        CommonLoadingUtils.getInstance().closeFunction();
                        if (obj != null) {
                            UserModel userModel = (UserModel) obj;

                            CommonUserHelper.saveUserData(userModel);
                            ToastUtils.show("登录成功", mContext);
                            Intent intent = new Intent();
                            intent.setAction("login_app");
                            App.getInstance().sendBroadcast(intent);
                            RegistActivity.this.finish();

                        } else {
                            ToastUtils.show("登录失败 数据异常", mContext);
                        }
                    }
                }, flagTime);


            }

            @Override
            public void onFaile(Object obj) {
                ToastUtils.show("登录失败 网络请求异常", mContext);
                CommonLoadingUtils.getInstance().closeFunction();
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SMSSDK.unregisterEventHandler(mEventHandler);
    }
}
